package com.cb.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cb.eduservice.entity.EduSubject;
import com.cb.eduservice.entity.excel.SubjectData;
import com.cb.eduservice.entity.subject.OneSubject;
import com.cb.eduservice.entity.subject.TwoSubject;
import com.cb.eduservice.listener.SubjectExcelListener;
import com.cb.eduservice.mapper.EduSubjectMapper;
import com.cb.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Cebb
 * @since 2020-06-22
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream stream = file.getInputStream();
            EasyExcel
                    .read(stream, SubjectData.class, new SubjectExcelListener(subjectService))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneAndTwoSubject() {
        // 查询一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneEduSubject = baseMapper.selectList(wrapperOne);

        // 查询二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoEduSubject = baseMapper.selectList(wrapperTwo);

        List<OneSubject> result = new ArrayList<>(32);
        for (int i = 0; i < oneEduSubject.size(); i++) {
            EduSubject one = oneEduSubject.get(i);
            OneSubject oneSubject = new OneSubject();
            // 将两个对象中相同字段的属性 , 复制到oneSubject中
            BeanUtils.copyProperties(one,oneSubject);

            // 处理二级目录
            List<TwoSubject> curOneSubjectChildrenList = new ArrayList<>();
            String parentId = oneSubject.getId();
            for (int j = 0; j < twoEduSubject.size(); j++) {
                EduSubject two = twoEduSubject.get(j);
                if (two.getParentId().equals(parentId)) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(two,twoSubject);
                    curOneSubjectChildrenList.add(twoSubject);
                }
            }
            oneSubject.setChildren(curOneSubjectChildrenList);
            result.add(oneSubject);
        }

        return result;
    }
}
